<?php
namespace control;
/*
*班组档案类
*/

class teamClass extends adIndexClass
{
    private const page = 'team';
    private const table = 'team';
    private const tableMx = 'team_detail';
    private const title = '班组档案';
    public array $stateOption = ['启用', '停用'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "班组编号",
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '班组名称',
                        'width' => 250,
                    ],
                    'manager'         => [
                        'name'  => '班组组长',
                        'width' => 250,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ],
                    'time'          => [
                        'name'  => '创建日期',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "班组编号" => text(array("name" => "orderNo")),
                    "班组名称"   => text(array("name" => "deptName")),
                    "班组组长"   => selectMultiple(array("name" => "manager", 'table' => 'staff', 'where' => "state !='离职'", "sqlId" => 'stid', 'sqlField' => 'name')),
                ],
                [
                    "创建日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>启用</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>停用</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
            "name" => $this->post('deptName'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "manager" => $this->post('manager'),
            'coid'=>self::$coid
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'updateTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'manager':
                        $row[] = self::findStaff($array['manager']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $type = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否修改所选数据状态为：" . $type,
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => "状态切换", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $state = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (!in_array($state, ['启用', '停用'])) {
            $json['warn'] = "类型错误";
        } else {
            $field = [
                'state' => $state,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$state}】， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $tr[] = ['', '员工编号', '员工名称', '班组分配系数', '计时单价('.static::$unit.'/小时)'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $staff = query('staff',"stid = '$array[stid]'");
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this)").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'stid[]', 'value' => $array['stid'])) ,
                $staff['orderNo'],
                $staff['name'],
                text(array('name' => 'rate[]', 'type'=>'number','value' => $array['rate'])),
                text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'),'value' => self::lostZero($array['price'],'pricePrecision'))),
            ];
        }
        $table = $this->listTable(array('tr' => $tr, 'end' => true));
        $tableBut = <<<efo
               <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name=teamEditForm]').serialize())">选择员工</span>
efo;

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "班组编号：" => text(["name" => "orderNo",  "value" => $info['orderNo']]),
                    must . "班组名称：" => text(["name" => "name",  "value" => $info['name']]),
                    must."班组组长：" =>selectMultiple(array("name" => "manager",'value'=>$info['manager'], "title" => "请选择", 'table' => 'staff', 'where' => "state !='离职'", "sqlId" => 'stid', 'sqlField' => 'name')),
                    "绑定生产线：" =>selectMultiple(array("name" => "lineId",'value'=>$info['lineId'], "title" => "请选择", 'table' => 'product_line', 'where' => "state ='启用' and coid = '".self::$coid."'", "sqlId" => 'id', 'field'=>"concat(workshop,'-',name) as name,id",'sqlField' => 'name')),
                ],
                [
                    "备注：" => textarea(["name" => "text","value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '班组成员',
            'button' => $tableBut,
            'html' => $table,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        //返回
        return $this->tab($data).$this->js();
    }

    public function js(){
        return <<<eof
<script>
function addRow(){
     $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
         $('#teamAddMx').hide();
         $("#materialTable tbody").append(res.html);
         resetNumber($("#materialTable"))
    },'json');
}
</script>
eof;

    }
    /**
     *
     * @return bool|string
     */
    public function addMx()
    {
        $html =
            selectMultiple(["name" => "jobId", 'table' => "job", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '职位']) .
            text(array("name" => "name", "title" => "姓名")) .
            text(array("name" => "tel", "title" => "电话")) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))).
            hidden(array('name' => 'staffId', 'value' => $this->post('stid') ? implode(',', $this->post('stid')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     *添加物料
     */
    public function addMxSearch()
    {
        $staffId= $this->post('staffId') ? explode(',', $this->post('staffId')) : [];
        $where = " stid not in ('" . implode("','", $staffId) . "') and state !='离职'";
        $and = '';
        $like = [
            'name' => $this->post('name'),
            'tel' => $this->post('tel'),
        ];
        $equal = [
            'jobId' => $this->post('jobId'),
        ];
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "staff",
            "where" => $where,
            'pageNum' => 50,
            "order" => "`time` ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, '部门', '职位', '姓名', '手机号码'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['stid']),
            );
            $job = query('job',"id = '$array[jobId]'");
            $department = query('department',"id = '$job[departmentId]'");
            $tr[] = array(
                $this->dominate($dominate),
                $department['name'],
                $job['name'],
                $array['name'],
                $array['tel'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>".
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择物料';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $staff = query('staff', "stid = '$mxId'");
                $id = self::getId();
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'stid[]', 'value' => $mxId)) ,
                    $staff['orderNo'],
                    $staff['name'],
                    text(array('name' => 'rate[]', 'type'=>'number','value' => '')),
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'),'value' => '')),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $staffIdArr = $this->post('stid');
        $rateArr = $this->post('rate');
        $priceArr = $this->post('price')?:[];
        $field = [
            'text' => $this->post('text'),
            'orderNo' => $this->post('orderNo'),
            'name' => $this->post('name'),
            'manager' => $this->post('manager'),
            'lineId' => $this->post('lineId'),
        ];
        $annotation = [
            'orderNo' => '班组编号',
            'name' => '班组名称',
            'manager' => '班组组长',
        ];
        $rules = [
            'orderNo' => 'required',
            'name' => 'required',
            'manager' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        $warn = '';
        foreach ($priceArr as $price){
            if (!empty($price) && ($price < 0)){
                $warn = '单价格式错误';
                break;
            }
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择成员';
        } elseif (static::is_null_array($staffIdArr)) {
            $json['warn'] = '请选择成员';
        } elseif(static::total(array('table'=>self::table,"where"=>"name = '$field[name]' and coid = '".self::$coid."' and id !='$id'")) >0){
            $json['warn'] = '已存在此名称的班组';
        }elseif(static::total(array('table'=>self::table,"where"=>"orderNo = '$field[orderNo]' and coid = '".self::$coid."' and id !='$id'")) >0){
            $json['warn'] = '已存在此编号的班组';
        }elseif($warn){
            $json['warn'] = $warn;
        }else {
            $this->startTrans();
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'state' => '启用',
                    'coid'=>self::$coid,
                    'stid' => self::$stid,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }

            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableMx, "id = '$nid'");
                $priceArr[$k] = $priceArr[$k]?:0;
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'stid' => $staffIdArr[$k],
                            'rate' => $rateArr[$k],
                            'price' => $priceArr[$k],
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => $nid,
                            'coid'=>self::$coid,
                            'orderId' => $id,
                            'stid' => $staffIdArr[$k],
                            'rate' => $rateArr[$k],
                            'price' => $priceArr[$k],
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑用户",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
                $state = $info['state'] == '停用' ? '启用' : '停用';
                $button[] = [
                    "name" => $state,
                    "type" => "点击事件",
                    'title' => '修改状态',
                    "fun" => "layer('" . $this->get('cla') . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$state}'})",
                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '停用') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }

            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
            $tr[] = ['员工编号', '员工名称', '班组分配系数','计时单价('.static::$unit.'/小时)'];
            foreach ($result['array'] as $index => $val) {
                $staff = query('staff',"stid = '$val[stid]'");
                $tr[] = [ $staff['orderNo'], $staff['name'], $val['rate'], self::lostZero($val['price'],'pricePrecision')];
            }
            $line = query('product_line',"id = '$info[lineId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "班组编号" => $info['orderNo'],
                        "班组名称" => $info['name'],
                        "班组组长" => self::findStaff($info['manager']),
                        "绑定生产线" => $line['workshop'].'-'.$line['name'],
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                    array(
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" =>$info['time'],
                        "状态" => $info['state'],
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '班组成员',
                'html' => $this->listTable(array('tr' => $tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }



    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '停用') {
                    $warn = "不是停用状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】，班组名称【{$info['name']}】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}
